import { defineStore } from "pinia";
import { ref, computed } from 'vue'
import { useUserStore } from "./user";
import { getCartAPI, addCartAPI, delCartAPI, comixCartAPI } from "@/api/cart";
import { ElMessage } from "element-plus";
export const useCartStore = defineStore('cart', () => {
    //添加购物车
    const cartList = ref([])
    const userStore = useUserStore()
    const Login = computed(() => userStore.userinfo.token)
    const addCart = async (goods) => {
        const { skuId, count } = goods
        if (Login.value) {
            await addCartAPI({ skuId, count })
            updateCart()
        } else {
            const item = cartList.value.find(item => item.skuId === goods.skuId)
            if (item) {
                item.count++
            }
            else cartList.value.push(goods)
            ElMessage
        }
    }
    //删除购物车
    const delCart = async (skuId) => {
        if (Login.value) {
            delCartAPI([skuId])
            updateCart()
        } else {
            const idx = cartList.value.findIndex(item => item.skuId === skuId)
            cartList.value.splice(idx, 1)
        }
    }
    //清空购物车
    const cleanCart = () => {
        cartList.value = []
    }
    const changeSingle = (id, selected) => {
        const item = cartList.value.find(item => item.skuId === id)
        item.selected = selected
    }
    const updateCart = async () => {
        const res = await getCartAPI()
        cartList.value = res.result
    }
    //全选功能：
    //法一：const changeAll = () => { cartList.value.filter(item => { item.allChange = !item.allChange; item.selected = !item.selected }) }
    const changeAll = (selected) => { cartList.value.forEach(item => item.selected = selected) }
    //计算属性
    const allcount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    const allprice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

    const allChange = computed(() => cartList.value.every(item => item.selected))
    const changeCount = computed(() => cartList.value.filter(item => item.selected === true).reduce((a, c) => a + c.count, 0))
    const changePrice = computed(() => cartList.value.filter(item => item.selected === true).reduce((a, c) => a + c.count * c.price, 0))
    return {
        cartList,
        addCart,
        delCart,
        allcount,
        allprice,
        allChange,
        changeCount,
        changePrice,
        changeSingle,
        changeAll,
        updateCart,
        cleanCart
    }
},
    {
        persist: true,
    }
)